package com.yf.controller.api;

import com.yf.annotation.IgnoreAuth;
import com.yf.entity.UserEntity;
import com.yf.entity.WxUser;
import com.yf.response.R;
import com.yf.service.TokenService;
import com.yf.service.UserService;
import com.yf.service.WxAppService;
import com.yf.service.WxWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiLoginController {

    /**
     * 小程序登录
     *
     * @param encryptedData 小程序getUserInfo获取
     * @param code          wxLogin获取
     * @param iv            初始向量  小程序getUserInfo获取
     * @param parentId      分享的用户
     * @return
     */
    @RequestMapping("/wx/app/login")
    @IgnoreAuth
    public R wxAppLogin(String encryptedData, String code, String iv, @RequestParam(required = false) Long parentId) {
        //先获取key
        WxUser wxUser = wxAppService.getOpenIdAndSessionKey(code);
        //解密
        wxUser = wxAppService.getWxUser(encryptedData, wxUser.getSessionKey(), iv);
        //查询
        UserEntity userEntity = userService.findByUnionId(wxUser.getUnionId());
        if (userEntity != null) {//验证登录
            userService.validateLogin(userEntity);
        } else {//不存在用户 注册
            userEntity = userService.registerVistor(wxUser, parentId);
        }
        String userToken = tokenService.createToken(userEntity.getId());
        return R.ok("成功", userToken);
    }


    /**
     * 微信web端登录
     *
     * @param code     通过链接获取
     * @param parentId 分享的用户
     * @return
     */
    @RequestMapping("/wx/web/login")
    @IgnoreAuth
    public R wxWebLogin(String code, @RequestParam(required = false) Long parentId) {
        //先获取key
        WxUser wxUser = wxWebService.getWxUser(code);
        //查询
        UserEntity userEntity = userService.findByUnionId(wxUser.getUnionId());
        if (userEntity != null) {//验证登录
            userService.validateLogin(userEntity);
        } else {//不存在用户 注册
            userEntity = userService.registerVistor(wxUser, parentId);
        }
        String userToken = tokenService.createToken(userEntity.getId());
        return R.ok("成功", userToken);
    }


    /**
     * 开发阶段测试登录
     * 默认登录当前用
     *
     * @param code 模拟登录的用户ID
     * @return
     */
    @RequestMapping("/wx/test/login")
    @IgnoreAuth
    public R testLogin(Long code) {
        UserEntity userEntity = userService.get(code);
        String userToken = tokenService.createToken(userEntity.getId());
        return R.ok("成功", userToken);
    }


    @Autowired
    private WxAppService wxAppService;

    @Autowired
    private WxWebService wxWebService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

}
